package com.aiden.app.common.widget.time

import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.bigkoo.pickerview.view.BasePickerView
import com.bigkoo.pickerview.view.WheelTime
import com.contrarywind.view.WheelView
import com.aiden.app.common.R
import com.aiden.app.common.extension.setVisible
import com.aiden.app.common.util.LogUtils
import java.text.ParseException
import java.util.*

class TimePickerView(pickerOptions: CustomPickerOptions) : BasePickerView(pickerOptions.context), View.OnClickListener {

    private var wheelTime: WheelTime? = null //自定义控件
    private val TAG_SUBMIT = "submit"
    private val TAG_CANCEL = "cancel"
    private lateinit var wheelExtras: WheelView

    init {
        mPickerOptions = pickerOptions
        initView(pickerOptions.context)
    }

    private fun initView(context: Context) {
        setDialogOutSideCancelable()
        initViews()
        initAnim()

        if (mPickerOptions.customListener == null) {
            LayoutInflater.from(context).inflate(R.layout.layout_custom_pickerview_time, contentContainer)

            //顶部标题
            val tvTitle = findViewById(R.id.tvTitle) as TextView
            val rv_top_bar = findViewById(R.id.rv_topbar) as RelativeLayout

            //确定和取消按钮
            val btnSubmit = findViewById(R.id.btnSubmit) as Button
            val btnCancel = findViewById(R.id.btnCancel) as Button

            wheelExtras = findViewById(R.id.extras) as WheelView

            btnSubmit.tag = TAG_SUBMIT
            btnCancel.tag = TAG_CANCEL

            btnSubmit.setOnClickListener(this)
            btnCancel.setOnClickListener(this)

            //设置文字
            btnSubmit.text = if (TextUtils.isEmpty(mPickerOptions.textContentConfirm)) context.resources.getString(R.string.pickerview_submit) else mPickerOptions.textContentConfirm
            btnCancel.text = if (TextUtils.isEmpty(mPickerOptions.textContentCancel)) context.resources.getString(R.string.pickerview_cancel) else mPickerOptions.textContentCancel
            tvTitle.text = if (TextUtils.isEmpty(mPickerOptions.textContentTitle)) "" else mPickerOptions.textContentTitle//默认为空

            //设置color
            btnSubmit.setTextColor(mPickerOptions.textColorConfirm)
            btnCancel.setTextColor(mPickerOptions.textColorCancel)
            tvTitle.setTextColor(mPickerOptions.textColorTitle)
            rv_top_bar.setBackgroundColor(mPickerOptions.bgColorTitle)

            //设置文字大小
            btnSubmit.textSize = mPickerOptions.textSizeSubmitCancel.toFloat()
            btnCancel.textSize = mPickerOptions.textSizeSubmitCancel.toFloat()
            tvTitle.textSize = mPickerOptions.textSizeTitle.toFloat()

        } else {
            mPickerOptions.customListener.customLayout(LayoutInflater.from(context).inflate(mPickerOptions.layoutRes, contentContainer))
        }
        // 时间转轮 自定义控件
        val timePickerView = findViewById(R.id.timepicker) as LinearLayout
        timePickerView.setBackgroundColor(mPickerOptions.bgColorWheel)

        initWheelTime(timePickerView)
    }

    private fun initWheelTime(timePickerView: LinearLayout) {
        wheelTime = WheelTime(timePickerView, mPickerOptions.type, mPickerOptions.textGravity, mPickerOptions.textSizeContent)
        val tvLabelYear = findViewById(R.id.tv_label_year)
        val tvLabelMonth = findViewById(R.id.tv_label_month)
        val tvLabelDay = findViewById(R.id.tv_label_day)
        val tvLabelHour = findViewById(R.id.tv_label_hour)
        val tvLabelMinute = findViewById(R.id.tv_label_minute)
        val tvLabelSecond = findViewById(R.id.tv_label_second)
        val labelArr = arrayOf(tvLabelYear, tvLabelMonth, tvLabelDay, tvLabelHour, tvLabelMinute, tvLabelSecond)
        mPickerOptions.type.forEachIndexed { index, b ->
            labelArr[index].setVisible(b)
        }
        if (mPickerOptions.timeSelectChangeListener != null) {
            wheelTime!!.setSelectChangeCallback {
                try {
                    val date = WheelTime.dateFormat.parse(wheelTime!!.time)
                    mPickerOptions.timeSelectChangeListener.onTimeSelectChanged(date)
                } catch (e: ParseException) {
                    e.printStackTrace()
                }
            }
        }

        wheelTime!!.isLunarMode = mPickerOptions.isLunarCalendar

        if (mPickerOptions.startYear != 0 && mPickerOptions.endYear != 0
                && mPickerOptions.startYear <= mPickerOptions.endYear) {
            setRange()
        }

        //若手动设置了时间范围限制
        if (mPickerOptions.startDate != null && mPickerOptions.endDate != null) {
            if (mPickerOptions.startDate.getTimeInMillis() > mPickerOptions.endDate.getTimeInMillis()) {
                throw IllegalArgumentException("startDate can't be later than endDate")
            } else {
                setRangDate()
            }
        } else if (mPickerOptions.startDate != null) {
            if (mPickerOptions.startDate.get(Calendar.YEAR) < 1900) {
                throw IllegalArgumentException("The startDate can not as early as 1900")
            } else {
                setRangDate()
            }
        } else if (mPickerOptions.endDate != null) {
            if (mPickerOptions.endDate.get(Calendar.YEAR) > 2100) {
                throw IllegalArgumentException("The endDate should not be later than 2100")
            } else {
                setRangDate()
            }
        } else {//没有设置时间范围限制，则会使用默认范围。
            setRangDate()
        }

        setTime()
        wheelTime?.let {
            it.setLabels(mPickerOptions.label_year, mPickerOptions.label_month, mPickerOptions.label_day, mPickerOptions.label_hours, mPickerOptions.label_minutes, mPickerOptions.label_seconds)
//            it.setTextXOffset(mPickerOptions.x_offset_year, mPickerOptions.x_offset_month, mPickerOptions.x_offset_day,
//                    mPickerOptions.x_offset_hours, mPickerOptions.x_offset_minutes, mPickerOptions.x_offset_seconds)
            it.setCyclic(mPickerOptions.cyclic)
            it.setDividerColor(mPickerOptions.dividerColor)
            it.setDividerType(mPickerOptions.dividerType)
            it.setLineSpacingMultiplier(mPickerOptions.lineSpacingMultiplier)
            it.setTextColorOut(mPickerOptions.textColorOut)
            it.setTextColorCenter(mPickerOptions.textColorCenter)
            it.isCenterLabel(mPickerOptions.isCenterLabel)
            LogUtils.e("TImePickerView", "normal item height = ${it.view.findViewById<WheelView>(R.id.year).itemHeight}")
        }
        setOutSideCancelable(mPickerOptions.cancelable)

        if ((mPickerOptions as CustomPickerOptions).extrasArray.isNotEmpty()) {
            val extrasArray = (mPickerOptions as CustomPickerOptions).extrasArray
            wheelExtras.adapter = ArrayWheelAdapter<String>(extrasArray)
//            wheelExtras.adapter = NumericWheelAdapter(1, 30)
//            wheelExtras.setLabel("测试")
            wheelExtras.setGravity(mPickerOptions.textGravity)
            wheelExtras.setCyclic(false)
            wheelExtras.setDividerType(mPickerOptions.dividerType)
            wheelExtras.setDividerColor(mPickerOptions.dividerColor)
            wheelExtras.setLineSpacingMultiplier(mPickerOptions.lineSpacingMultiplier)
            wheelExtras.setTextColorOut(mPickerOptions.textColorOut)
            wheelExtras.setTextColorCenter(mPickerOptions.textColorCenter)
            wheelExtras.setTextSize(mPickerOptions.textSizeContent.toFloat())
            wheelExtras.isCenterLabel(mPickerOptions.isCenterLabel)
            wheelExtras.currentItem = 0
            LogUtils.e("TimePickerView", "custom item height = ${wheelExtras.itemHeight}")
        } else {
            wheelExtras.setVisible(false)
        }
    }


    /**
     * 设置默认时间
     */
    fun setDate(date: Calendar) {
        mPickerOptions.date = date
        setTime()
    }

    /**
     * 设置可以选择的时间范围, 要在setTime之前调用才有效果
     */
    private fun setRange() {
        wheelTime!!.startYear = mPickerOptions.startYear
        wheelTime!!.endYear = mPickerOptions.endYear

    }

    /**
     * 设置可以选择的时间范围, 要在setTime之前调用才有效果
     */
    private fun setRangDate() {
        wheelTime!!.setRangDate(mPickerOptions.startDate, mPickerOptions.endDate)
        initDefaultSelectedDate()
    }

    private fun initDefaultSelectedDate() {
        //如果手动设置了时间范围
        if (mPickerOptions.startDate != null && mPickerOptions.endDate != null) {
            //若默认时间未设置，或者设置的默认时间越界了，则设置默认选中时间为开始时间。
            if (mPickerOptions.date == null || mPickerOptions.date.getTimeInMillis() < mPickerOptions.startDate.getTimeInMillis()
                    || mPickerOptions.date.getTimeInMillis() > mPickerOptions.endDate.getTimeInMillis()) {
                mPickerOptions.date = mPickerOptions.startDate
            }
        } else if (mPickerOptions.startDate != null) {
            //没有设置默认选中时间,那就拿开始时间当默认时间
            mPickerOptions.date = mPickerOptions.startDate
        } else if (mPickerOptions.endDate != null) {
            mPickerOptions.date = mPickerOptions.endDate
        }
    }

    /**
     * 设置选中时间,默认选中当前时间
     */
    private fun setTime() {
        val year: Int
        val month: Int
        val day: Int
        val hours: Int
        val minute: Int
        val seconds: Int
        val calendar = Calendar.getInstance()

        if (mPickerOptions.date == null) {
            calendar.timeInMillis = System.currentTimeMillis()
            year = calendar.get(Calendar.YEAR)
            month = calendar.get(Calendar.MONTH)
            day = calendar.get(Calendar.DAY_OF_MONTH)
            hours = calendar.get(Calendar.HOUR_OF_DAY)
            minute = calendar.get(Calendar.MINUTE)
            seconds = calendar.get(Calendar.SECOND)
        } else {
            year = mPickerOptions.date.get(Calendar.YEAR)
            month = mPickerOptions.date.get(Calendar.MONTH)
            day = mPickerOptions.date.get(Calendar.DAY_OF_MONTH)
            hours = mPickerOptions.date.get(Calendar.HOUR_OF_DAY)
            minute = mPickerOptions.date.get(Calendar.MINUTE)
            seconds = mPickerOptions.date.get(Calendar.SECOND)
        }

        wheelTime!!.setPicker(year, month, day, hours, minute, seconds)
    }


    override fun onClick(v: View) {
        val tag = v.tag as String
        if (tag == TAG_SUBMIT) {
            returnData()
        } else if (tag == TAG_CANCEL) {
            if (mPickerOptions.cancelListener != null) {
                mPickerOptions.cancelListener.onClick(v)
            }
        }
        dismiss()
    }

    fun returnData() {
        if (mPickerOptions.timeSelectListener != null) {
            try {
                val date = WheelTime.dateFormat.parse(wheelTime!!.time)
                mPickerOptions.timeSelectListener.onTimeSelect(date, clickView)
            } catch (e: ParseException) {
                e.printStackTrace()
            }
        }
        if (mPickerOptions is CustomPickerOptions && (mPickerOptions as CustomPickerOptions).onTimeSelectWithExtraListener != null) {
            try {
                val date = WheelTime.dateFormat.parse(wheelTime!!.time)
                (mPickerOptions as CustomPickerOptions).onTimeSelectWithExtraListener?.onTimeSelect(date, wheelExtras.currentItem, clickView)
            } catch (e: ParseException) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 动态设置标题
     *
     * @param text 标题文本内容
     */
    fun setTitleText(text: String) {
        val tvTitle = findViewById(R.id.tvTitle) as TextView
        if (tvTitle != null) {
            tvTitle.text = text
        }
    }

    /**
     * 目前暂时只支持设置1900 - 2100年
     *
     * @param lunar 农历的开关
     */
    fun setLunarCalendar(lunar: Boolean) {
        try {
            val year: Int
            val month: Int
            val day: Int
            val hours: Int
            val minute: Int
            val seconds: Int
            val calendar = Calendar.getInstance()
            calendar.time = WheelTime.dateFormat.parse(wheelTime!!.time)
            year = calendar.get(Calendar.YEAR)
            month = calendar.get(Calendar.MONTH)
            day = calendar.get(Calendar.DAY_OF_MONTH)
            hours = calendar.get(Calendar.HOUR_OF_DAY)
            minute = calendar.get(Calendar.MINUTE)
            seconds = calendar.get(Calendar.SECOND)

            wheelTime!!.isLunarMode = lunar
            wheelTime!!.setLabels(mPickerOptions.label_year, mPickerOptions.label_month, mPickerOptions.label_day,
                    mPickerOptions.label_hours, mPickerOptions.label_minutes, mPickerOptions.label_seconds)
            wheelTime!!.setPicker(year, month, day, hours, minute, seconds)
        } catch (e: ParseException) {
            e.printStackTrace()
        }

    }

    fun isLunarCalendar(): Boolean {
        return wheelTime!!.isLunarMode
    }


    override fun isDialog(): Boolean {
        return mPickerOptions.isDialog
    }
}